from tkinter import *


class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.result = StringVar('')
        self.input_label = Label(self, text='输入一个十六进制正整数：')
        self.input_label.grid(row=0, column=0)
        self.hexadecimal_entry = Entry(self, text='1A')
        self.hexadecimal_entry.grid(row=0, column=1)
        self.output_label = Label(self, text='该十六进制数转化成十进制数为')
        self.output_label.grid(row=1, column=0)
        self.decimal_entry = Label(self, textvariable=self.result)
        self.decimal_entry.grid(row=1, column=1)
        self.convert_button = Button(self, text='转换', command=self.convert)
        self.convert_button.grid(row=2, column=1)

    def convert(self):
        hex_number = self.hexadecimal_entry.get()
        flag = True
        i = 0
        result = 0
        ch = hex_number[0]  # ques
        while i < len(hex_number) and flag:
            if '0' <= ch <= '9':
                result = result * 16 + int(ch)
            elif 'A' <= ch <= 'F':
                result = result * 16 + ord(ch) - ord('A') + 10
            elif 'a' <= ch <= 'f':
                result = result * 16 + ord(ch) - ord('a') + 10
            else:
                flag = False
            i += 1
            if i == len(hex_number):
                break
            ch = hex_number[i]  # ques

        if flag:
            self.result.set(str(result))
        else:
            self.result.set('输入错误')


app = Application()
app.master.title('进制转换')
app.mainloop()
